import { Component, OnInit, Input } from '@angular/core';
import {
  FormLayout,
  DValidateRules,
  DFormControlRuleDirective,
} from "ng-devui/form";
import { LoadingService } from 'ng-devui';
import { DialogService } from 'ng-devui/modal'
import { AuthGuardService } from '../../../@core/auth-guard-service.guard'
import { Router } from '@angular/router';

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.scss']
})
export class TransferComponent implements OnInit {
  @Input() data: any;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  constructor(private dialogService: DialogService,
    private loadingService: LoadingService,
    private authGuardService: AuthGuardService,
    private router: Router) { }

  private showLoading: any
  address: any
  userId = parseInt(localStorage.getItem('userId'))

  formRules: { [key: string]: DValidateRules } = {
    rule: {
      message: "请检查表单！",
      messageShowType: "text",
    },
    address: {
      validators: [
        { required: true, message: "被转赠人地址不能为空" },
      ],
    },
  };

  openDialog() {
    const results = this.dialogService.open({
      id: 'dialog-service',
      width: '300px',
      maxHeight: '300px',
      title: '温馨提示',
      content: "您确定转赠该藏品吗？",
      backdropCloseable: true,
      dialogtype: 'warning',
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          handler: ($event: Event) => {
            this.transform(results)
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          }
        }
      ],
      data: {
      }
    })
  }

  ngOnInit(): void {
  }

  cancel() {
    this.data.close()
  }

  submitForm({ valid }) {
    if (valid) {
      this.openDialog()
    }
  }

  transform(results) {
    this.showLoading = this.loadingService.open({
      message: '正在转赠藏品，请稍等……'
    })
    this.authGuardService.assetsTranfer(this.userId, this.data.collectionNum, this.address).subscribe((res) => {
      this.showLoading.loadingInstance.close();
      results.modalInstance.hide()
      if (res.code == 0) {
        this.authGuardService.showModalPanel('success', res.msg)
        this.data.close()
        this.router.navigate(['/collections'])
      }
      else {
        this.authGuardService.showModalPanel('warning', res.msg)
      }
    })
  }
}
